import React from 'react';
import { 
  Upload, 
  Button, 
  Typography,
  Alert,
  Space,
  message,
  Progress,
  Card,
  List
} from 'antd';
import { 
  LoadingOutlined,
  InboxOutlined,
  DeleteOutlined,
  UploadOutlined,
  FileImageOutlined,
  DownloadOutlined
} from '@ant-design/icons';
import { pdfService } from '../services/pdfService';
import type { UploadProps } from 'antd';
import styles from './ImagesToPDF.module.css';
import PageHeader from './PageHeader';

const { Dragger } = Upload;
const { Title, Text } = Typography;

const ImagesToPDF: React.FC = () => {
  const [fileList, setFileList] = React.useState<File[]>([]);
  const [converting, setConverting] = React.useState(false);
  const [error, setError] = React.useState<string>('');
  const [progress, setProgress] = React.useState(0);
  const [convertedFile, setConvertedFile] = React.useState<{
    blob: Blob;
    fileName: string;
  } | null>(null);

  const handleFileSelect = (info: any) => {
    const files = info.fileList.map((f: any) => f.originFileObj);
    
    setError('');
    setProgress(0);
    setConvertedFile(null);

    // 验证文件
    const invalidFiles = files.filter((file: File) => !pdfService.validateImageFile(file));
    if (invalidFiles.length > 0) {
      setError('请上传有效的图片文件（JPG/PNG，每个文件小于10MB）');
      return;
    }

    setFileList(files);
  };

  const handleConvert = async () => {
    if (fileList.length === 0) {
      message.warning('请先选择图片文件');
      return;
    }

    try {
      setConverting(true);
      setError('');
      setProgress(0);
      setConvertedFile(null);
      
      const response = await pdfService.imagesToPDF(fileList);
      
      if (response.code === 200 && response.data?.blob && response.data?.fileName) {
        setProgress(100);
        setConvertedFile({
          blob: response.data.blob,
          fileName: response.data.fileName
        });
        message.success('转换成功！');
      } else {
        throw new Error('转换失败，请重试');
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '转换过程出错';
      setError(errorMessage);
      message.error('转换失败：' + errorMessage);
    } finally {
      setConverting(false);
    }
  };

  const handleDownload = async () => {
    if (!convertedFile) return;

    const hide = message.loading('准备保存...', 0);
    
    try {
      const success = await pdfService.saveFileWithDialog(
        convertedFile.blob, 
        convertedFile.fileName
      );

      hide();
      
      if (success) {
        message.success('文件保存成功');
      } else {
        message.info('已取消保存');
      }
    } catch (error) {
      hide();
      message.error('文件保存失败，请重试');
      console.error('Download error:', error);
    }
  };

  const uploadProps: UploadProps = {
    multiple: true,
    accept: '.jpg,.jpeg,.png',
    showUploadList: false,
    beforeUpload: () => false,
    onChange: handleFileSelect,
  };

  return (
    <div className={styles.container}>
      <PageHeader title="图片转PDF" />
      <Card className={styles.converterCard}>
        <Title level={4} className={styles.cardTitle}>
          图片转PDF
        </Title>

        <div className={styles.uploadSection}>
          {fileList.length === 0 ? (
            <Dragger {...uploadProps} className={styles.draggerContainer}>
              <p className="ant-upload-drag-icon">
                <InboxOutlined className={styles.uploadIcon} />
              </p>
              <p className={styles.uploadText}>
                点击或拖拽图片文件到此区域
              </p>
              <p className={styles.uploadHint}>
                支持JPG、PNG格式，每个文件不超过10MB
              </p>
            </Dragger>
          ) : (
            <div className={styles.fileList}>
              <List
                dataSource={fileList}
                renderItem={(file, index) => (
                  <List.Item
                    className={styles.fileItem}
                    actions={[
                      <Button
                        key="delete"
                        icon={<DeleteOutlined />}
                        onClick={() => {
                          const newFiles = fileList.filter((_, i) => i !== index);
                          setFileList(newFiles);
                          if (newFiles.length === 0) {
                            setError('');
                            setProgress(0);
                            setConvertedFile(null);
                          }
                        }}
                      >
                        删除
                      </Button>
                    ]}
                  >
                    <List.Item.Meta
                      avatar={<FileImageOutlined className={styles.fileIcon} />}
                      title={file.name}
                      description={`${(file.size / (1024 * 1024)).toFixed(2)}MB`}
                    />
                  </List.Item>
                )}
              />
              <div className={styles.actionBar}>
                <Space>
                  <Upload {...uploadProps}>
                    <Button icon={<UploadOutlined />}>
                      添加图片
                    </Button>
                  </Upload>
                  <Button
                    type="primary"
                    icon={converting ? <LoadingOutlined /> : <FileImageOutlined />}
                    onClick={handleConvert}
                    loading={converting}
                    disabled={!!error}
                  >
                    {converting ? '转换中...' : '开始转换'}
                  </Button>
                </Space>
              </div>
            </div>
          )}
        </div>

        {error && (
          <Alert
            message="错误"
            description={error}
            type="error"
            showIcon
            className={styles.alert}
          />
        )}

        {converting && (
          <div className={styles.progressContainer}>
            <Progress 
              percent={progress} 
              status={progress === 100 ? "success" : "active"}
              strokeColor={{
                '0%': '#108ee9',
                '100%': '#87d068',
              }}
            />
          </div>
        )}

        {convertedFile && (
          <Alert
            message={
              <Space size="middle" align="center" className={styles.convertedInfo}>
                <Text type="success">
                  文件已转换完成
                </Text>
                <Button 
                  type="primary"
                  icon={<DownloadOutlined />}
                  onClick={handleDownload}
                >
                  保存文件
                </Button>
              </Space>
            }
            type="success"
            showIcon
          />
        )}
      </Card>
    </div>
  );
};

export default ImagesToPDF; 